<?php
	/* -------------------------------------------------------------------
	IOU - expense sharing system 
	Copyright (C) 2009 - Mischa Spelt (m.spelt@gmail.com)
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
	------------------------------------------------------------------- */

	function createPassword($userID) {
		$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
		$password = "";
		for($i = 0; $i < 8; ++$i)
			$password .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
		global $_SERVER;
		global $db;
		$user = $db->q("tuple SELECT DisplayName, Email FROM Users WHERE ID = %i", $userID);
		$db->q("UPDATE Users SET Password = PASSWORD(%s) WHERE ID = %i", $password, $userID);
		mail("{$user['DisplayName']} <{$user['Email']}>", "Password for IOU.", "Dear {$user['DisplayName']}. \n\n A new password has been generated for the IOU system at " . getURL() . ". It is: {$password}. Please log in and change the password as soon as possible.", "From: IOU system <{$user['Email']}>");
	}

	function addUser($login, $display, $email, $by = null) {
		global $db;
		if($db->q("value SELECT COUNT(*) FROM Users WHERE LOWER(Login) = %s", strtolower($login))) 
			print "Username already taken.";
		elseif($db->q("value SELECT COUNT(*) FROM Users WHERE LOWER(Email) = %s", strtolower($email))) 
			print "E-mail address already in use.";
		else {
			$id = $db->q("returnid INSERT INTO Users(Login, DisplayName, Email, CreatedBy) VALUES(%s, %s, %s, %.)", strtolower($login), $display, $email, $by);
			createPassword($id);
			print "The user account was created. The initial password has been sent to the specified e-mail address.";
		}
	}

?>
